from flask import Flask
from flask_sockets import Sockets
import datetime
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
import ast
import json
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r'/*': {"origins": "*"}})
sockets = Sockets(app)
userList=[]
def checkUserList(item,ws):
    index=0
    for i in range(len(userList)):
        if(userList[index]['fromId']==item['fromId']):
            return {'result':True,'index':index}
        index+=1
    return {'result':False}

def sendMsg(item):
    return json.dumps({'fromId': item['fromId'], 'fromName':item['fromName'], 'content': item['content'], 'type': item['type'], 'toId': item['toId'], 'toName': item['toName'], 'headIcon': item['headIcon']})
# 登录方法
def login(item,ws):
    #userList[item['fromId']]=ws
    # for i in userList:
    #     userList[i].send(json.dumps(item))
    data=checkUserList(item,ws)
    if(data['result']==False):
        item['ws']=ws
        userList.append(item)
    else:
        userList[data['index']]['ws']=ws
    for i in userList:
        i['ws'].send(sendMsg(item))
def send_to_sb(msg):
    for i in userList:
        if(i['fromId']==msg['fromId'] or i['fromId']==msg['toId']):
            i['ws'].send(sendMsg(msg))

#离开方法
def leave(item):
    index=-1
    # for i in range(len(userList)):
    #     if userList[i]['fromId'] == item['fromId']:
    #         del userList[i]
    #         break
    data = checkUserList(item)
    if (data['result'] == False):
        return
    else:
        del userList[data['index']]

#消息方法
@sockets.route('/test')
def test(ws):
    while not ws.closed:
        msg = ws.receive()
        msg=ast.literal_eval(msg) #转换成字典
        print(msg)

    #<geventwebsocket.websocket.WebSocket object at 0x000002310D340CA0>
        #print(f'i received:{msg["id"]}')
        if msg:
            now = datetime.datetime.now().isoformat()
            #operation = {'login': login(msg), 'leave': leave(msg), 'message': ""}
            if(msg['type']=='login'):
                login(msg,ws)
            elif(msg['type']=='msg'):
                if(msg['toId']=='all'):
                    for i in userList:
                        try:
                            userList[i].send(json.dumps(msg))
                        except:
                            continue
                else:
                    send_to_sb(msg)
            elif(msg['type']=='leave'):
                leave(msg)
            #ws.send(str(msg['content']) )
            print(type(msg))

            #print(f'i sent:{now}')
            print('userList',userList)
@app.route('/getUser',methods=['get'])
def fn():
    newList=[]
    for i in userList:
        newList.append({'fromId': i['fromId'], 'fromName': i['fromName'], 'headIcon': i['headIcon']})
    return {"status": 200, "data": newList, "message": "登陆成功"}


if __name__ == "__main__":
    server = pywsgi.WSGIServer(('0.0.0.0', 8540), application=app, handler_class=WebSocketHandler)
    print('server started')
    server.serve_forever()

